package com.fast.fast.common.gateway.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 树工具类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
public class TreeUtils {

    /**
     * 获取包括所有子节点信息的父节点(通过递归地为父节点添加子节点对象)
     *
     * @param list   数据集合
     * @param parent 父节点
     * @return
     */
    public static <T> T listNodes(List<T> list, T parent) {
        list.stream().filter(o -> {
                    try {
                        Field pidField = o.getClass().getDeclaredField("pid");
                        Field idField = parent.getClass().getSuperclass().getDeclaredField("id");
                        pidField.setAccessible(true);
                        idField.setAccessible(true);
                        Long pid = (Long) pidField.get(o);
                        Long id = (Long) idField.get(parent);
                        return pid.equals(id);
                    } catch (Exception e) {
                        return false;
                    }
                })
                .forEach(o -> {
                    try {
                        Field childrenField = parent.getClass().getDeclaredField("children");
                        childrenField.setAccessible(true);
                        if (childrenField.get(parent) == null) {
                            childrenField.set(parent, new ArrayList<>());
                        }
                        List<T> children = (List<T>) childrenField.get(parent);
                        // 递归添加父节点的子节点
                        children.add(listNodes(list, o));
                    } catch (Exception ignored) {
                    }
                });
        return parent;
    }

}
